package com.googlecode.restitory.api.servlet;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import com.googlecode.restitory.gae.filter.wrapper.ResponseAdapter;

public class JsonProtocolFilter implements Filter {

	public void destroy() {

	}

	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {

		String callback = req.getParameter("callback");
		if (callback == null) {
			callback = "";
		}
		callback = callback.trim();
		if (callback.length() == 0) {
			chain.doFilter(req, resp);
			return;
		}

		HttpServletResponse r = (HttpServletResponse) resp;
		ResponseAdapter wrapper = new ResponseAdapter(r);
		chain.doFilter(req, wrapper);

		String contentType = wrapper.getContentType();
		contentType = ServletHelper.getMediaType(contentType);
		if (!"application/json".equals(contentType)) {
			byte[] buffer = wrapper.getBuffer();
			r.setContentLength(buffer.length);
			ServletOutputStream out = r.getOutputStream();
			out.write(buffer);
			return;
		}

		String charset = wrapper.getCharacterEncoding();
		byte[] cbStart = (callback + "(").getBytes(charset);
		byte[] cbEnd = ");".getBytes(charset);

		r.setContentType("application/javascript");
		r.setCharacterEncoding(charset);

		byte[] buffer = wrapper.getBuffer();
		r.setContentLength(buffer.length + cbStart.length + cbEnd.length);

		ServletOutputStream out = r.getOutputStream();
		out.write(cbStart);
		if (buffer.length > 0) {
			out.write(buffer);
		}
		out.write(cbEnd);
	}

	public void init(FilterConfig config) throws ServletException {

	}

}
